/**
 * Background Script 配置服务
 * 专门处理配置管理的服务
 */

import { ExtensionConfig } from "@utils/types";
import { STORAGE_KEYS } from "@utils/constants";

// 默认配置
export const DEFAULT_CONFIG: ExtensionConfig = {
  theme: "auto",
  autoHighlight: false,
  enabledFeatures: ["highlight-links", "count-elements", "panel"],
  version: "1.0.0",
};

/**
 * 配置管理服务类
 */
export class ConfigManager {
  private static instance: ConfigManager;
  private config: ExtensionConfig | null = null;

  private constructor() {}

  static getInstance(): ConfigManager {
    if (!ConfigManager.instance) {
      ConfigManager.instance = new ConfigManager();
    }
    return ConfigManager.instance;
  }

  /**
   * 获取配置
   */
  async getConfig(): Promise<ExtensionConfig> {
    if (!this.config) {
      try {
        const stored = await browser.storage.local.get(STORAGE_KEYS.CONFIG);
        this.config = {
          ...DEFAULT_CONFIG,
          ...stored[STORAGE_KEYS.CONFIG],
        };
      } catch (error) {
        console.warn("Failed to load config, using default:", error);
        this.config = { ...DEFAULT_CONFIG };
      }
    }
    return this.config!;
  }

  /**
   * 更新配置
   */
  async updateConfig(updates: Partial<ExtensionConfig>): Promise<void> {
    const currentConfig = await this.getConfig();
    this.config = { ...currentConfig, ...updates };

    try {
      await browser.storage.local.set({
        [STORAGE_KEYS.CONFIG]: this.config,
      });
    } catch (error) {
      console.error("Failed to save config:", error);
      throw error;
    }
  }

  /**
   * 重置配置到默认值
   */
  async resetConfig(): Promise<void> {
    this.config = { ...DEFAULT_CONFIG };
    try {
      await browser.storage.local.set({
        [STORAGE_KEYS.CONFIG]: this.config,
      });
    } catch (error) {
      console.error("Failed to reset config:", error);
      throw error;
    }
  }

  /**
   * 获取特定功能是否启用
   */
  async isFeatureEnabled(feature: string): Promise<boolean> {
    const config = await this.getConfig();
    return config.enabledFeatures.includes(feature);
  }
}
